/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-11-11 15:57:31
 * @LastEditTime: 2024-11-12 13:00:22
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 
 * @FilePath: \markdown-magic\src\pages\Pdf\service\unlock.js
 * @Copyright 版权声明
 */
// const fs = require('fs');
// const path = require('path');
// const { PDFDocument } = require('pdf-lib');
// const pdfjsLib = require('pdfjs-dist');

import * as pdfjsLib from "pdfjs-dist"
import * as workerSrc from "pdfjs-dist/build/pdf.worker.min?url";
import { PDFDocument } from 'pdf-lib'
// import * as fontkit from 'fontkit'
// import fontkit from 'https://cdn.skypack.dev/@pdf-lib/fontkit@^1.0.0?dts'

// 设置 workerSrc
pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc.default;

export const unlockAndProcessPdf = async (encryptedPdfBytes, password) => {
  return new Promise(async (resolve, reject) => {
    try {
  
      // 使用 pdfjs-dist 解密 PDF 文件
      const loadingTask = pdfjsLib.getDocument({
        data: encryptedPdfBytes,
        password: password,
      });
  
      const pdf = await loadingTask.promise;
  
      // 检查是否成功解密
      if (pdf.isEncrypted) {
        // throw new Error('Failed to decrypt the PDF file');
        resolve({
          code: 1,
          message: '无法解密PDF文件',
        })
      }
  
      // 将解密后的 PDF 转换为 Uint8Array
      const decryptedPdfBytes = await pdf.saveDocument(pdf.getData());
  
      // 使用 pdf-lib 加载解密后的 PDF 文档
      // const pdfDoc = await PDFDocument.load(decryptedPdfBytes, { ignoreEncryption: true });
      const pdfDoc = await PDFDocument.load(decryptedPdfBytes);
  
      // // 进行进一步的操作，例如添加文本或图像
      // const page = pdfDoc.getPages()[0];
      // if (page) {
      //   // 注册 fontkit 实例
      //   PDFDocument.registerFontkit(fontkit);
      //   const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf'
      //   const fontBytes = await fetch(url).then((res) => res.arrayBuffer())
      //   const { width, height } = page.getSize();
      //   const fontSize = 30;
      //   const font = await pdfDoc.embedFont(fontBytes);
      //   const textColor = [0, 0, 0];
  
      //   const text = 'This PDF has been unlocked and modified';
      //   const x = 50;
      //   const y = height - 50;
      //   page.drawText(text, {
      //     x,
      //     y,
      //     size: fontSize,
      //     font,
      //     color: textColor,
      //   });
      // }
  
      // 保存修改后的 PDF 文档
      const pdfBytes = await pdfDoc.save();
  
      console.log('PDF unlocked and processed successfully');
      // return pdfBytes;
      resolve(pdfBytes)
    } catch (error) {
      console.error('Error unlocking and processing PDF:', error);
      resolve({
        code: 1,
        message: '解锁和处理PDF时失败',
      })
    }
  })
}